package com.codecrane.core.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 公共上传控制器
 * Created by crane on 16/9/17.
 */
@Slf4j
@Controller
@RequestMapping("/upload")
public class UploaderController {

    //TODO 增加进度监控

    @Value("${app_upload_store_path}")
    private String uploadStorePath;

    /**
     * 图片上传(单个)
     *
     * @param uploadFile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/image", method = RequestMethod.POST)
    public AjaxReturn uploadImageFile(@RequestParam("imageFile") MultipartFile uploadFile) {
        AjaxReturn result = Ajax.fail();
        if (!uploadFile.isEmpty()) {
            JSONObject fileJson = getUploadFileInfo(uploadFile, "image");
            result.setOk(true).setData(fileJson);
        }
        return result;
    }

    /**
     * 图片批量上传(多个)
     *
     * @param uploadFile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/images", method = RequestMethod.POST)
    public AjaxReturn uploadImagesFile(@RequestParam("imagesFile") MultipartFile[] uploadFile) {
        AjaxReturn result = Ajax.fail();
        if (null != uploadFile && uploadFile.length > 0) {

            JSONArray response = new JSONArray();
            for (MultipartFile imageFile : uploadFile) {
                JSONObject fileJson = getUploadFileInfo(imageFile, "image");
                response.add(fileJson);
            }
            result.setOk(true).setData(response);
        }
        return result;
    }

    /**
     * 附件上传(单个)
     *
     * @param uploadFile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/attachment", method = RequestMethod.POST)
    public AjaxReturn uploadAttachmentsFile(@RequestParam("attachmentFile") MultipartFile uploadFile) {
        AjaxReturn result = Ajax.fail();
        if (!uploadFile.isEmpty()) {

            JSONObject fileJson = getUploadFileInfo(uploadFile, "attachment");
            result.setOk(true).setData(fileJson);
        }
        return result;
    }

    /**
     * 附件批量上传(多个)
     *
     * @param uploadFile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/attachments", method = RequestMethod.POST)
    public AjaxReturn uploadAttachmentsFile(@RequestParam("attachmentsFile") MultipartFile[] uploadFile) {
        AjaxReturn result = Ajax.fail();
        if (null != uploadFile && uploadFile.length > 0) {
            JSONArray response = new JSONArray();
            for (MultipartFile attachmentsFile : uploadFile) {
                JSONObject fileJson = getUploadFileInfo(attachmentsFile, "attachment");
                response.add(fileJson);
            }
            result.setOk(true).setData(response);
        }
        return result;
    }

    /**
     * 生成上传文件指纹
     *
     * @param file
     * @param fileType 文件类型
     * @return
     */
    private JSONObject getUploadFileInfo(MultipartFile file, String fileType) {
        JSONObject fileJson = new JSONObject();
        fileJson.put("fileRealName", file.getOriginalFilename());
        String fileSuffix = FilenameUtils.getExtension(file.getOriginalFilename());
        fileJson.put("fileSuffix", fileSuffix);
        fileJson.put("fileSize", file.getSize());
        fileJson.put("fileType", file.getContentType());

        String fileStoreName = System.currentTimeMillis() + String.valueOf(RandomUtils.nextInt(10000, 99999)) + "." + fileSuffix;
        fileJson.put("fileStoreName", fileStoreName);

        try {

            String targetPath = "";
            if ("image".equals(fileType)) {
                targetPath = "images";
            } else if ("attachment".equals(fileType)) {
                targetPath = "attachments";
            }
            String fileStorePath = uploadStorePath + targetPath + SystemUtils.FILE_SEPARATOR + fileStoreName;
            fileJson.put("fileStorePath", fileStorePath);
            file.transferTo(new File(fileStorePath));
        } catch (IOException e) {
            log.error("文件上传异常! FileInfo:{}", fileJson);
            log.error("文件上传异常! FileType:{} Exception:{}", fileType, e.getMessage());
        }

        return fileJson;
    }
}
